package top.smallway.lightbandassistant_app.adapter;

import static com.blankj.utilcode.util.ActivityUtils.startActivity;
import static top.smallway.lightbandassistant_app.method.Method.unmarshalSongData;
import static top.smallway.lightbandassistant_app.method.Method.secondsToTimeFormat;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import top.smallway.lightbandassistant_app.R;
import top.smallway.lightbandassistant_app.UI.AboutSong;
import top.smallway.lightbandassistant_app.data.Song_Data;
import top.smallway.lightbandassistant_app.data.Message;
import top.smallway.lightbandassistant_app.network.Search;

/**
 * 帖子列表适配器
 * 负责显示用户发布的帖子列表，包括帖子内容、发布时间、歌曲KEY等信息的展示
 * 实现帖子查看和歌曲跳转功能
 */
public class PostsAdapter extends RecyclerView.Adapter<PostsAdapter.MyViewHolder> {
    // 是否启用加载更多功能
    private boolean mIsLoadMoreEnabled = false;
    // 帖子数据列表
    private List<Message> data;
    // 上下文对象
    private final Context context;
    /**
     * 消息处理Handler
     * 处理歌曲详情跳转和错误提示等异步操作
     */
    private final Handler mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void dispatchMessage(@NonNull android.os.Message msg) {
            super.dispatchMessage(msg);
        }

        @Override
        public void handleMessage(@NonNull android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case -1:
                    Song_Data song_data = (Song_Data) msg.obj;
                    startActivity(AboutSong.fromDataToIntent(context, song_data));
                    break;
                case -3:
                    Toast.makeText(context, "歌曲不存在", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    /**
     * 构造函数
     * @param data 帖子数据列表
     * @param context 上下文对象
     */
    public PostsAdapter(List<Message> data, Context context) {
        this.data = data;
        this.context = context;
    }

    /**
     * 创建ViewHolder
     * @param parent 父视图组
     * @param viewType 视图类型
     * @return 返回创建的ViewHolder
     */
    @NonNull
    @Override
    public PostsAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.songs_items3, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull PostsAdapter.MyViewHolder holder, int position) {
        if (data != null) {
            Message message = data.get(position);
            holder.username.setText(message.getAuthor());
            holder.ip.setText("IP属地：" + message.getIp());
            LocalDateTime dateTime = LocalDateTime.parse(message.getCreated_at(), DateTimeFormatter.ISO_LOCAL_DATE_TIME);
            // 格式化为其他格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDateTime = dateTime.format(formatter);

            holder.time.setText("发布时间：" + formattedDateTime);
            if (Objects.equals(message.getKey(), "")) {
                holder.song_name.setText("未填写KEY");
                final int[] num = {0};
                holder.look.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (num[0] == 0) {
                            num[0]++;
                            Toast.makeText(context, "🌹作者未填写KEY🌹", Toast.LENGTH_SHORT).show();
                        } else if (num[0] > 0 && num[0] < 5) {
                            num[0]++;
                            Toast.makeText(context, "😓都说啦没填KEY😓", Toast.LENGTH_SHORT).show();
                        } else if (num[0] >= 5 && num[0] < 10) {
                            num[0]++;
                            Toast.makeText(context, "😤都说了没填没填没填！！😤", Toast.LENGTH_SHORT).show();
                        } else if (num[0] >= 10 && num[0] < 15) {
                            num[0]++;
                            Toast.makeText(context, "🫤不是？你怎么还点啊？🫤", Toast.LENGTH_SHORT).show();
                        } else if (num[0] >= 15 && num[0] < 20) {
                            num[0]++;
                            Toast.makeText(context, "😫不是？你有完没完？😫", Toast.LENGTH_SHORT).show();
                        } else if (num[0] >= 20 && num[0] < 25) {
                            num[0]++;
                            Toast.makeText(context, "😑你不无聊吗？😑", Toast.LENGTH_SHORT).show();
                        } else {
                            num[0]++;
                            Toast.makeText(context, "😒好了好了，真拿你没办法😒", Toast.LENGTH_SHORT).show();
                        }

                    }
                });
            } else {
                String key = message.getKey();
                holder.song_name.setText("歌曲KEY：" + key);
                holder.look.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                android.os.Message message = new android.os.Message();
                                try {
                                    String output = Search.getsong(key, 0);
                                    Song_Data Song_Data = unmarshalSongData(output);
                                    if (Song_Data == null) {
                                        message.what = -3;
                                    } else {
                                        message.what = -1;
                                        message.obj = Song_Data;
                                    }
                                } catch (IOException e) {
                                    Log.e("KEY搜歌", "错误原因", e);
                                }
                                mHandler.sendMessage(message);
                            }
                        }).start();
                    }
                });
            }
            holder.title.setText(message.getTitle());
            holder.context.setText(message.getContent());
            Glide.with(holder.itemView.getContext()).load(message.getHash()).placeholder(R.drawable.pgbar).error(R.mipmap.logo).into(holder.img);


        }
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    @SuppressLint("NotifyDataSetChanged")
    /**
     * 更新帖子数据
     * @param newData 新的帖子数据列表
     */
    public void updateData(List<Message> newData) {
        if (data == null) {
            data = new ArrayList<>();
        }

        data.addAll(newData);
        notifyDataSetChanged();
    }

    /**
     * 视图持有者类
     * 用于缓存帖子项的视图组件
     */
    public class MyViewHolder extends RecyclerView.ViewHolder {
        private final ImageView img;
        private final TextView username, ip, song_name, title, context, time;
        private final Button look;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            img = itemView.findViewById(R.id.img);
            username = itemView.findViewById(R.id.username);
            ip = itemView.findViewById(R.id.ip);
            song_name = itemView.findViewById(R.id.song_name);
            title = itemView.findViewById(R.id.title);
            context = itemView.findViewById(R.id.context);
            look = itemView.findViewById(R.id.look);
            time = itemView.findViewById(R.id.time);
        }
    }

    /**
     * 设置是否启用加载更多功能
     * @param enabled 是否启用
     */
    public void setLoadMoreEnabled(boolean enabled) {
        mIsLoadMoreEnabled = enabled;
        notifyDataSetChanged();
    }
}
